#!/usr/bin/env python
# -*- coding:utf-8 -*-
import mimetypes
import os.path

from flask_restful import Resource, reqparse
from flask import Flask, request, jsonify, send_file, Response

from controller.pptGenController import PptGenController
from service.pptBaseService import PptBaseService
from utils import commons
from utils.loggings import loggings
from utils.response_code import RET, error_map_EN


class PptBaseOtherResource(Resource):

    @classmethod
    def download_ppt(cls):
        """
        下载用户生成的PPT文件
        :return: 返回PPT文件给用户进行下载
        """
        # 解析请求参数
        parser = reqparse.RequestParser()
        parser.add_argument('gen_id', location='args', required=True, help='user_id 参数类型不正确或缺失')


        kwargs = parser.parse_args()

        # 获取参数
        gen_id = kwargs.get('gen_id')

        # try:
        # 获取PPT文件的存储路径
        ppt = PptGenController.get(gen_id=gen_id)
        print(ppt)

        if  ppt["code"]!=RET.OK:
            return jsonify(code=RET.NODATA, message="PPT 文件不存在", data={})
        ppt=ppt["data"][0]
        location=ppt["location"]
        ppt_location = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), location)
        with open(ppt_location, 'rb') as f:
            file_stream = f.read()
        response = Response(file_stream)
        mime_type = mimetypes.guess_type(location)[0]
        print(mime_type)
        print(location.split('\\')[-1].encode('UTF-8').decode('latin1'))
        response.headers['Content-Type'] = mime_type
        response.headers['Content-Disposition'] = 'attachment; filename={}'.format(
        location.split('\\')[-1].encode('UTF-8').decode('latin1'))
        return response

        #
        # except Exception as e:
        #     # 记录异常
        #     loggings.exception(1, f"Error occurred while downloading PPT: {e}")
        #     return jsonify(code=RET.IOERR, message="系统异常，请稍后再试", data={'error': str(e)})

    @classmethod
    def get_chat_list(cls):
        res = PptBaseService.get_chat_list()
        return jsonify(code=res['code'], message=res['message'], data=res['data'])
